<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>滑块验证通过</title>
	</head>
	<style>
		.box{
			position: relative;
			text-align: center;
			margin-top: 100px;
			width: 500px;
			border: 1px solid #C9C9C9;
			height: 30px;
		}
		.btn{
			z-index: 2;
			position: absolute;
			width: 30px;
			height: 30px;
			left: 0px;
			top: 0px;
			background: url(箭头.png) no-repeat;
			background-size: 100% 100%;
			/* 移入变成手指的标志cursor: pointer; */
			cursor: pointer;
			
		}
		.text{
			z-index: 4;
			text-align: center;
			font-size: 18px;
			line-height: 30px;
			vertical-align: middle;
		}
		.backg{
			z-index: -1;
			position: absolute;
			left: 0px;
			top: 0px;
			width: 0px;
			height: 30px;
			background-color: forestgreen;
		}
	</style>

	<body>
		<div class="box">
			<div class="btn"></div>
			<div class="text">请拖动滑块向右解锁</div>
			<div class="backg"></div>
		</div>

		<script type="text/javascript">
			//页面加载事件
			window.onload = function() {
				//封装选择器
				function $(name) {
					return document.querySelector(name);
				}
				//获取按钮节点
				var btn = $(".btn");
				var box = $(".box");
				var text = $(".text");
				var backg = $(".backg");
				//判断验证是否通过标识
				var flag = false;

				//给按钮添加鼠标按下事件
				btn.onmousedown = function(e) {
					//获取按下后的鼠标坐标
					var downx = e.clientX;
					//给鼠标添加鼠标移入事件
					btn.onmousemove = function(e) {
						//鼠标移动的位置
						var movex = e.clientX;
						//小滑块移动的位置
						var btnX = movex - downx;
						if (btnX > 0) {
							//重新设置按钮x轴上的位置
							this.style.left = btnX + "px";
							//
							backg.style.width = btnX + "px";

							if (btnX >= box.offsetWidth - this.offsetWidth) {
								//验证是否通过的标识
								flag = true;
								text.innerText = "验证通过";
								text.style.color = "#fff";
								//验证通过，将按钮的事件清除
								this.onmousedown = null;
								this.onmousemove = null;

							}
						}
					}
					//按钮移出时若不为true时也会回到原点
					btn.onmouseleave = function() {
						if (!flag) {
							//删除按钮的移入事件
							this.onmousemove = null;
							//修改背景大小为0
							backg.style.width = "0px";
							//使按钮回到原点
							btn.style.left = "0px";
						}
					}
				}
				//鼠标点击事件
				btn.onmouseup = function() {
					if (!flag) {
						this.onmousemove = null;
						btn.style.left ="0px";
						backg.style.width ="0px";
					}
				}
			}
		</script>


	</body>
</html>
